/* eslint-disable no-param-reassign */
import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import { Button, Dialog, Form } from '@alifd/next';
import { t } from '@lingui/macro';
import { observable } from 'mobx';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid, TitleGrid } from '../stores/definitions';
// import AttachmentPanel from './AttachmentPanel';

const FromItem = Form.Item;

const formItemLayout = {
  labelCol: {
    fixedSpan: 8,
  },
  wrapperCol: {
    span: 14,
  },
  style: { marginBottom: 20 },
};

function CouponForm({ id, modal, onSubmit, onCancel }) {
  const { couponStore: store } = useStore();
  const [coupon] = useState(() => observable({}));
  const [isViewMode] = useState(modal[0] === 'view');
  const formProps = isViewMode ? { field: false } : {};
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    if (id) {
      (async () => {
        const data = await store.get(id);
        editCtx.origin = _.cloneDeep(data);
        _.assign(coupon, data);
      })();
    } else {
      _.set(coupon, 'enable', true);
      _.set(coupon, 'transferable', false);
    }
  }, []);

  if (!coupon) return <></>;

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(coupon, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: CouponForm.jsx:69 _ errors:', errors);
      return;
    }
    onSubmit?.(coupon);
  };

  return (
    <Form
      colon
      isPreview={isViewMode}
      {...formProps}
      value={coupon}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <FieldsGrid
        formData={coupon}
        mode={modal[0]}
        itemLayout={{ ...formItemLayout, labelAlign: 'left' }}
        columns={1}
        fields={[
          'name', 'type',
          // 'totalQuantity',
          // 'bizType', 'startTime', 'endTime', 'transferable'
          'enable', 'description', 'ruleDescription',
        ]}
      />

      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>

    </Form>
  );
}

export default observer(CouponForm);

